package com.wjj.controller;

import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.support.RateLimitExceededException;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import java.util.Objects;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author junjun Wang
 * @Date Create in 14:26 2023/12/7
 **/
@RestController

public class DefinedZuulErrorController implements ErrorController {

	@Override
	public String getErrorPath() {
		return "/error";
	}

	/**
	 * 覆盖掉默认的ErrorController
	 *
	 * @return
	 */
	@RequestMapping("/error")
	public String myError() {
		RequestContext context = RequestContext.getCurrentContext();
		ZuulException exception = (ZuulException) context.getThrowable();

		if (Objects.nonNull(exception)
				&& exception.getCause() instanceof RateLimitExceededException) {
			Route route = (Route) context.get("rateLimitRequestRoute");
			String path = route.getFullPath();
			return path + ":" + HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase();
		}
		return exception.toString();
	}
}